package com.doudou.oauth.token;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;

import java.time.Clock;
import java.util.LinkedHashMap;

/**
 * @Author: 傻男人
 * @Date: 2020/5/18 19:07
 * @Version: 1.0
 * @Description: 增强token 属性   可以向返回的token中添加其他信息
 */
public class CustomTokenEnhancer implements TokenEnhancer {

    @Autowired
    private RedisTemplate redisTemplate;

    Clock clock = Clock.systemUTC();

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        return preEnhance(accessToken,authentication);
    }

    protected OAuth2AccessToken preEnhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        OAuth2AccessToken oAuth2AccessToken = accessToken;

        OAuth2AccessToken token = (OAuth2AccessToken)redisTemplate.opsForValue().get(accessToken.getValue());
        redisTemplate.opsForValue().set(authentication,token);
        if(accessToken instanceof DefaultOAuth2AccessToken){
            ((DefaultOAuth2AccessToken)oAuth2AccessToken).setAdditionalInformation(new LinkedHashMap<String, Object>(){
                {
                    put("timeUTC",clock.millis());
                }
            });
        }
//        Map<String, Object> additionalInformation = new HashMap<>();
//        OAuth2Request oAuth2Request = authentication.getOAuth2Request();
//        if(oAuth2Request != null){
//            additionalInformation.put("resourceIds",oAuth2Request.getResourceIds());
//            additionalInformation.put("clientId",oAuth2Request.getClientId());
//            additionalInformation.put("scope",oAuth2Request.getScope());
//        }
//        Authentication userAuthentication = authentication.getUserAuthentication();
//        if(userAuthentication != null){
//            String userName = userAuthentication.getName();
//            User user = (User) userAuthentication.getPrincipal();
//            additionalInformation.put("userName", userName);
//            additionalInformation.put("roles", user.getAuthorities());
//            additionalInformation.put("organization", authentication.getName());
//        }
//        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInformation);
        return oAuth2AccessToken;
    }
}
